package com.masterclient.app.businessmodule.homemodule.fragment;

import android.Manifest;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.alibaba.android.vlayout.layout.SingleLayoutHelper;
import com.eoner.baselib.utils.status.StatusBarUtils;
import com.eoner.baselib.utils.toast.ToastUtil;
import com.eoner.baselibrary.widget.PermissionDialog;
import com.eoner.common.config.Config;
import com.eoner.managerlibrary.router.AroutePath;
import com.eoner.uikit.header.MyRefreshHead;
import com.masterclient.app.BaseFragment;
import com.masterclient.app.R;
import com.masterclient.app.base.CaptureActivity;
import com.masterclient.app.base.FragmentHostActivity;
import com.masterclient.app.businessmodule.homemodule.adapter.AdGroupAdapter;
import com.masterclient.app.businessmodule.homemodule.adapter.BannerAdapter;
import com.masterclient.app.businessmodule.homemodule.adapter.HotMeetAdapter;
import com.masterclient.app.businessmodule.homemodule.adapter.OnePicAdapter;
import com.masterclient.app.businessmodule.homemodule.adapter.OtherMeetAdapter;
import com.masterclient.app.businessmodule.homemodule.adapter.TabAdapter;
import com.masterclient.app.businessmodule.homemodule.contract.HomeContract;
import com.masterclient.app.businessmodule.homemodule.contract.HomePresenter;
import com.masterclient.app.businessmodule.homemodule.view.footer.HomeClassicFooter;
import com.masterclient.app.businessmodule.homemodule.view.holder.HomeViewHolder;
import com.masterclient.app.modules.income.model.HomeDataBean;
import com.masterclient.app.modules.search.SearchHistoryActivity;
import com.masterclient.app.utils.CommonUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class HomeFragment extends BaseFragment<HomePresenter> implements HomeContract.View {

    public static final int REQUEST_CODE = 111;

    @BindView(R.id.view_title)
    View viewTitle;
    @BindView(R.id.ic_scan)
    ImageView icScan;
    @BindView(R.id.ic_search)
    ImageView icSearch;
    @BindView(R.id.swipeLayout)
    SmartRefreshLayout swipeLayout;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.tv_help_txt)
    TextView tvHelpTxt;

    public static String TAG = "HomePageNewFragment";

    final List<DelegateAdapter.Adapter> adapters = new LinkedList<>();
    DelegateAdapter delegateAdapter;
    BannerAdapter adapter_banner;
    OnePicAdapter adapter_one_pic;
    TabAdapter adapter_tab;
    AdGroupAdapter adapter_adGroup;
    HotMeetAdapter adapter_hot_meet;
    OtherMeetAdapter adapter_other_meet;

    private RxPermissions rxPermissions;
    private String helpUrl;
    private String notifyType;
    private int page = 1;
    private List<HomeDataBean.HotEventItem> list = new ArrayList();

    public static HomeFragment newInstance() {
        return new HomeFragment();
    }

    @Override
    protected View getRootView(LayoutInflater inflater) {
        return inflater.inflate(R.layout.fragment_home, null);
    }

    @Override
    protected void initOnlyOnce() {
        super.initOnlyOnce();

        rxPermissions = new RxPermissions(getActivity());
        //2.设置状态栏
        StatusBarUtils.immersive(getActivity());
        StatusBarUtils.setPaddingSmart(getActivity(), viewTitle);
        swipeLayout.setRefreshHeader(new MyRefreshHead(getActivity()));
        swipeLayout.setRefreshFooter(new HomeClassicFooter(getActivity()));
        swipeLayout.setOnRefreshListener(refreshLayout -> {
            page = 1;
            mPresenter.getIndexData(page);
        });

        VirtualLayoutManager layoutManager = new VirtualLayoutManager(mContext);
        layoutManager.setInitialPrefetchItemCount(10);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setItemViewCacheSize(16);

        RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();
        recyclerView.setRecycledViewPool(viewPool);
        for (int i = 0; i < 13; i++) {
            viewPool.setMaxRecycledViews(i, 10);
        }
        delegateAdapter = new DelegateAdapter(layoutManager, false);
        recyclerView.setAdapter(delegateAdapter);

        mPresenter.getIndexData(page);
    }

    @OnClick({R.id.ic_scan, R.id.ic_search, R.id.view_home_issue})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.ic_scan:
                rxPermissions = new RxPermissions(getActivity());
                boolean hasPermissions = rxPermissions.isGranted(Manifest.permission.CAMERA);
                if (!hasPermissions) {
                    new PermissionDialog(getActivity(), "开启摄像头权限", "获取摄像头和相册权限以便扫码，请在下一个页面点击“允许”",
                            R.mipmap.icon_permission_phone, this::requestPermissions).show();
                } else {
                    Intent intent = new Intent(getActivity(), CaptureActivity.class);
                    intent.putExtra("isHome", true);
                    try {
                        getActivity().startActivityForResult(intent, 111);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;
            case R.id.ic_search:
                Intent intent = new Intent(mContext, SearchHistoryActivity.class);
                if (Config.search_term_keyword != null) {
                    intent.putExtra("hint_word", "");
                }
                startActivity(intent);
                break;
            case R.id.view_home_issue:
                if (!TextUtils.isEmpty(helpUrl)) {
                    CommonUtil.goAnyWhere(mContext, helpUrl, "", "", "", "", "");
                }
                break;
        }
    }

    private void requestPermissions() {
        rxPermissions
                .requestEach(Manifest.permission.CAMERA)
                .subscribe(permission -> { // will emit 2 Permission objects
                    if (permission.granted) {
                        // `permission.name` is granted !
                        Intent intent = new Intent(getActivity(), CaptureActivity.class);
                        intent.putExtra("isHome", true);
                        try {
                            getActivity().startActivityForResult(intent, 111);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else if (permission.shouldShowRequestPermissionRationale) {
                        // Denied permission without ask never again
                    } else {
                        // Denied permission with ask never again
                        // Need to go to the settings
                    }
                });
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
    }

    @Override
    public void showHomeList(HomeDataBean homeDataBean) {
        if (swipeLayout != null) {
            swipeLayout.finishRefresh();
        }
        if (list == null) {
            list = new ArrayList<>();
        }


        if (homeDataBean != null && !TextUtils.isEmpty(homeDataBean.helpUrl)) {
            tvHelpTxt.setText(homeDataBean.helpText);
            this.helpUrl = homeDataBean.helpUrl;
        }
        if (page == 1) {
            list.clear();
            list.addAll(homeDataBean.events);

            adapters.clear();
            delegateAdapter.setAdapters(adapters);
            recyclerView.setAdapter(delegateAdapter);

            addBannerAdapter(homeDataBean.adsRoll);
            addCapsulesAdapter(homeDataBean.adsJg);
            addOnePicAdapter(homeDataBean.adsJn);
            addPromotionsAdapter(homeDataBean.adsJg, homeDataBean.adsLeft, homeDataBean.adsRight);
            addHotMeetAdapter(homeDataBean.hotEvents, homeDataBean.hotText);
            addOtherMeetAdapter(list, homeDataBean.listText);

            delegateAdapter.setAdapters(adapters);
        } else {
            if (homeDataBean.events != null && homeDataBean.events.size() > 0) {
                swipeLayout.finishLoadMore();
                adapter_other_meet.setLoadMore(true);
                list.addAll(homeDataBean.events);
                adapter_other_meet.loadMore(list);
            } else {
                swipeLayout.finishLoadMoreWithNoMoreData();
                adapter_other_meet.setLoadMore(false);
            }
        }
    }

    @Override
    public void showHomeListFailed(String msg) {
        if (swipeLayout != null) {
            swipeLayout.finishRefresh(false);
        }
        ToastUtil.showToast(msg);
    }

    @Override
    public void subscribeSuccess() {
        if ("hot".equals(notifyType)) {
            adapter_hot_meet.notifyData();
        } else {
            adapter_other_meet.notifyData();
        }
    }

    @Override
    public void subscribeFailed(String msg) {
        ToastUtil.showToast(msg);
    }

    /**
     * 首页-banner
     */
    public void addBannerAdapter(List<HomeDataBean.HomeAdsItem> bannerBean) {
        if (adapters.contains(adapter_banner)) {
            adapter_banner.stopAutoPlay();
            adapters.remove(adapter_banner);
        }
        if (bannerBean != null && bannerBean.size() > 0) {
            SingleLayoutHelper layoutHelper = new SingleLayoutHelper();
            adapter_banner = new BannerAdapter(mContext, layoutHelper, 1, null, bannerBean) {
                @Override
                public HomeViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                    return new HomeViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.adapter_home_banner, parent, false));
                }

                @Override
                public void onBindViewHolder(HomeViewHolder holder, int position) {
                    super.onBindViewHolder(holder, position);
                }
            };
            adapters.add(adapter_banner);
        }
    }

    /**
     * 首页-胶囊区
     */
    public void addCapsulesAdapter(List<HomeDataBean.HomeAdsItem> capsules) {
        if (adapters.contains(adapter_tab)) {
            adapters.remove(adapter_tab);
        }
        if (capsules != null) {
            SingleLayoutHelper layoutHelper = new SingleLayoutHelper();
            adapter_tab = new TabAdapter(mContext, layoutHelper, 1, null, capsules) {
                @Override
                public HomeViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                    return new HomeViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.adapter_home_tab, parent, false));
                }

                @Override
                public void onBindViewHolder(HomeViewHolder holder, int position) {
                    super.onBindViewHolder(holder, position);
                }
            };
            adapters.add(adapter_tab);
        }
    }

    /**
     * 首页-单图
     */
    public void addOnePicAdapter(List<HomeDataBean.HomeAdsItem> leftAds) {
        if (adapters.contains(adapter_one_pic)) {
            adapters.remove(adapter_one_pic);
        }
        if (leftAds != null && leftAds.size() > 0) {
            SingleLayoutHelper layoutHelper = new SingleLayoutHelper();
            adapter_one_pic = new OnePicAdapter(getActivity(), layoutHelper, 1, null, leftAds) {
                @Override
                public HomeViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                    return new HomeViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.adapter_home_one_pic, parent, false));
                }

                @Override
                public void onBindViewHolder(HomeViewHolder holder, int position) {
                    super.onBindViewHolder(holder, position);
                }
            };
            adapters.add(adapter_one_pic);
        }
    }

    /**
     * 首页-Tab大促区
     */
    public void addPromotionsAdapter(List<HomeDataBean.HomeAdsItem> adsJg, List<HomeDataBean.HomeAdsItem> leftAds, List<HomeDataBean.HomeAdsItem> rightAds) {
        //大促区
        if (adapters.contains(adapter_adGroup)) {
            adapters.remove(adapter_adGroup);
        }
        if (leftAds != null && leftAds.size() > 0 && rightAds != null && rightAds.size() > 0) {
            boolean hasJg = false;
            if (adsJg != null && adsJg.size() > 0) {
                hasJg = true;
            }
            leftAds.addAll(rightAds);
            SingleLayoutHelper layoutHelper = new SingleLayoutHelper();
            adapter_adGroup = new AdGroupAdapter(getActivity(), layoutHelper, 1, null, leftAds, hasJg) {
                @Override
                public HomeViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                    return new HomeViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.adapter_home_three_pic, parent, false));
                }

                @Override
                public void onBindViewHolder(HomeViewHolder holder, int position) {
                    super.onBindViewHolder(holder, position);
                }
            };
            adapters.add(adapter_adGroup);
        }
    }

    /**
     * 首页-热门会场
     */
    public void addHotMeetAdapter(List<HomeDataBean.HotEventItem> capsules, String title) {
        if (adapters.contains(adapter_hot_meet)) {
            adapters.remove(adapter_hot_meet);
        }
        if (capsules != null) {
            SingleLayoutHelper layoutHelper = new SingleLayoutHelper();
            adapter_hot_meet = new HotMeetAdapter(mContext, layoutHelper, 1, null, capsules, title) {
                @Override
                public HomeViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                    return new HomeViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.adapter_home_hot_meet, parent, false));
                }

                @Override
                public void onBindViewHolder(HomeViewHolder holder, int position) {
                    super.onBindViewHolder(holder, position);
                }
            };
            adapter_hot_meet.setEventAdDataCallback((eventId, type) -> {
                notifyType = type;
                mPresenter.addSubscribe(eventId);
            });
            adapters.add(adapter_hot_meet);
        }
    }

    /**
     * 首页-分会场
     */
    public void addOtherMeetAdapter(List<HomeDataBean.HotEventItem> capsules, String title) {
        if (adapters.contains(adapter_other_meet)) {
            adapters.remove(adapter_other_meet);
        }
        if (capsules != null) {
            SingleLayoutHelper layoutHelper = new SingleLayoutHelper();
            adapter_other_meet = new OtherMeetAdapter(mContext, layoutHelper, 1, null, capsules, title) {
                @Override
                public HomeViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                    return new HomeViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.adapter_home_other_meet, parent, false));
                }

                @Override
                public void onBindViewHolder(HomeViewHolder holder, int position) {
                    super.onBindViewHolder(holder, position);
                }
            };
            adapter_other_meet.setEventAdDataCallback(new OtherMeetAdapter.EventAdDataCallback() {
                @Override
                public void adData() {
                    page++;
                    mPresenter.getIndexData(page);
                }

                @Override
                public void clickItem(String eventId, String type) {
                    notifyType = type;
                    mPresenter.addSubscribe(eventId);
                }
            });
            adapters.add(adapter_other_meet);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
